package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.DayNumAdapter;
import com.runen.infinitemovement.adapter.MyHozomAdapter;
import com.runen.infinitemovement.adapter.SignInAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MYHozomListEntity;
import com.runen.infinitemovement.model.entity.SignHzDayEntity;
import com.runen.infinitemovement.model.entity.SignInEntity;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.tool.AnimationUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.popupwind.TipsPopupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DayTaskActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.btn_finish)
    Button btnFinish;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.rv_msg_list)
    RecyclerView rvMsgList;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.rv_day)
    RecyclerView rvDay;
    @BindView(R.id.rv_sign_in)
    RecyclerView rvSignIn;
    @BindView(R.id.rv_sign_in2)
    RecyclerView rvSignIn2;
    @BindView(R.id.ll_hozom_finish)
    LinearLayout ll_hozom_finish;
    @BindView(R.id.tv_hozom_sum)
    TextView tv_hozom_sum;
    @BindView(R.id.iv_gantan)
    ImageView iv_gantan;
    private MyHozomAdapter myHozomAdapter;
    private MYHozomListEntity.DataBean hozomListEntity;
    private DayNumAdapter dayNumAdapter;
    private SignInAdapter signInAdapter;
    private SignInAdapter signInAdapter2;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_day_task;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        int height = CommonUtil.getStatusBarHeight(this);
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
                layoutParams.topMargin = height;
                rlTitle.setLayoutParams(layoutParams);
            }
        });
//        rlTitle.setPadding(0, height + 10, 0, 40);
        srl.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMsgList.setLayoutManager(layoutManager);
        myHozomAdapter = new MyHozomAdapter(this);
        rvMsgList.setAdapter(myHozomAdapter);

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvDay.setLayoutManager(layoutManager1);
        dayNumAdapter = new DayNumAdapter(this);
        rvDay.setAdapter(dayNumAdapter);

//        LinearLayoutManager layoutManager2 = new GridLayoutManager(this, 4);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        layoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvSignIn.setLayoutManager(layoutManager2);
        signInAdapter = new SignInAdapter(this);
        rvSignIn.setAdapter(signInAdapter);
        List<Integer> days = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            int day = i + 1;
            days.add(day);
        }
        signInAdapter.setNewInstance(days);

        LinearLayoutManager layoutManager3 = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        layoutManager3.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvSignIn2.setLayoutManager(layoutManager3);
        signInAdapter2 = new SignInAdapter(this);
        rvSignIn2.setAdapter(signInAdapter2);
        List<Integer> days2 = new ArrayList<>();
        for (int i = 4; i < 7; i++) {
            int day2 = i + 1;
            days2.add(day2);
        }
        signInAdapter2.setNewInstance(days2);


//        initData();
        myHozomAdapter.setOnClickListener(new MyHozomAdapter.OnClickListener() {
            @Override
            public void onClick(MYHozomListEntity.DataBean.MissionStatesBean item, int point) {
                if (item.canBeGot) {
                    Intent intent = new Intent();
                    switch (item.goTo) {
                        //0没有 1资讯 2动态 3运动 4我的长征路 5活动 6每日知识竞赛答题 7兑换步数 8邀请好友 9团队点赞 10党史新闻 11打卡分享
                        case 0:
                            onStepFor();
//                            startActivity(new Intent(DayTaskActivity.this, StepsForActivity.class));
                            break;
                        case 1:
                        case 2:
                            intent.setClass(DayTaskActivity.this, CompanyCricleActivity.class);
                            startActivity(intent);
                            break;
                        case 3:
                            MainActivity.checkFragment(88);
                            finish();
                            break;
                        case 4:
                            intent.setClass(DayTaskActivity.this, MyTheLongMarchRoadActivity.class);
                            intent.putExtra("userId", UserAPI.getUserId());
                            startActivity(intent);
                            break;
                        case 5:
                            intent.setClass(DayTaskActivity.this, CompanyCricleActivity.class);
                            intent.putExtra("userId", UserAPI.getUserId());
                            startActivity(intent);
                            break;
                        case 6:
                            intent.setClass(DayTaskActivity.this, WebActivity.class);
                            intent.putExtra("LINK_URL", String.format(Constant.H5_ANSWER_REWARD, UserAPI.getUserToken()));
                            startActivity(intent);
                            break;
                        case 7:
                            onStepFor();
                            break;
                        case 8:
                            intent.setClass(DayTaskActivity.this, InviteFriendsActivity.class);
                            startActivity(intent);
                            break;
                        case 9:
                            intent.setClass(DayTaskActivity.this, MyTeamActivityV2.class);
                            startActivity(intent);
                            break;
                        case 10:
                            intent.setClass(DayTaskActivity.this, WebActivity.class);
                            intent.putExtra("LINK_URL", String.format(Constant.H5_HISTORY_LIST, UserAPI.getUserToken()));
                            startActivity(intent);
                            break;
                        case 11:
                            intent.setClass(DayTaskActivity.this, PunchCardActivity.class);
                            startActivity(intent);
                            break;
                    }
                }
            }
        });

    }

    private void onStepFor() {
        showDialog();
        new UserAPI().stepsFor(new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
                if (response.getCode() == 0) {
                    ToastUtils.showShort(response.getMessage());
                    initData();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }

    private void goSignIn(MYHozomListEntity.DataBean.MissionStatesBean statesBean, int point) {
        new UserAPI().onSignIn(new BaseResultCallback<SignInEntity>() {
            @Override
            public void onResponse(SignInEntity response) {
                if (response.code == 0) {
                    ToastUtils.showShort(response.msg);
                    statesBean.button = "已签到";
                    myHozomAdapter.notifyItemChanged(point);
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        srl.setRefreshing(true);
        new UserAPI().onHozomList(new BaseResultCallback<MYHozomListEntity>() {
            @Override
            public void onResponse(MYHozomListEntity response) {
                srl.setRefreshing(false);
                hozomListEntity = response.data;
                signInAdapter.setDay(hozomListEntity.consecutiveCheckDays);
                signInAdapter2.setDay(hozomListEntity.consecutiveCheckDays);
                signInAdapter.notifyDataSetChanged();
                signInAdapter2.notifyDataSetChanged();
                String num = String.valueOf(hozomListEntity.consecutiveCheckDays);
//                int day = SharePreferenceUtils.getInt(DayTaskActivity.this, "singin_day");
                //筛选出当前登录人的打卡天数信息
                String day = "";
                try {
                    day = SharePreferenceUtils.getString(DayTaskActivity.this, SPCompat.SIGN_IN_DAY);
                } catch (Exception e) {
                    day = "";
                }
                List<SignHzDayEntity> list = new ArrayList<>();
                if (!TextUtils.isEmpty(day)) {
                    list = new Gson().fromJson(day, new TypeToken<List<SignHzDayEntity>>() {
                    }.getType());
                } else {
                    list.add(new SignHzDayEntity(UserAPI.getUserId(), 0));
                }
                int currentIndex = -1;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).userId.equals(UserAPI.getUserId())) {
                        currentIndex = i;
                    }
                }
                int dayNums = currentIndex == -1 ? 0 : list.get(currentIndex).day;
                if (dayNums < hozomListEntity.consecutiveCheckDays) {
//                    SharePreferenceUtils.putInt(DayTaskActivity.this, "singin_day", hozomListEntity.consecutiveCheckDays);
                    if (currentIndex == -1) {
                        list.add(new SignHzDayEntity(UserAPI.getUserId(), hozomListEntity.consecutiveCheckDays));
                    } else
                        list.get(currentIndex).day = hozomListEntity.consecutiveCheckDays;
                    SharePreferenceUtils.putString(DayTaskActivity.this,
                            SPCompat.SIGN_IN_DAY, new Gson().toJson(list));
                    String add_hozom = "火种数+%s";
                    switch (hozomListEntity.consecutiveCheckDays) {
                        case 1:
                            tv_hozom_sum.setText(String.format(add_hozom, 1));
                            break;
                        case 2:
                            tv_hozom_sum.setText(String.format(add_hozom, 2));
                            break;
                        case 3:
                            tv_hozom_sum.setText(String.format(add_hozom, 4));
                            break;
                        case 4:
                            tv_hozom_sum.setText(String.format(add_hozom, 5));
                            break;
                        case 5:
                            tv_hozom_sum.setText(String.format(add_hozom, 8));
                            break;
                        case 6:
                            tv_hozom_sum.setText(String.format(add_hozom, 10));
                            break;
                        case 7:
                            tv_hozom_sum.setText(String.format(add_hozom, 15));
                            break;
                        default:
                            tv_hozom_sum.setText(String.format(add_hozom, 15));
                            break;
                    }
                    AnimationUtils.showAndHiddenAnimation(ll_hozom_finish, AnimationUtils.AnimationState.STATE_SHOW, 3000);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(5000);
                                handler.sendEmptyMessage(2);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
                List<String> dayNum = new ArrayList<>();
                if (num.length() == 1) {
                    dayNum.add("0");
                    dayNum.add("0");
                } else if (num.length() == 2) {
                    dayNum.add("0");
                }
                dayNum.add(num);
                dayNumAdapter.setNewInstance(dayNum);
//                tvHozomNum.setText(String.valueOf(hozomListEntity.consecutiveCheckDays));
                if (hozomListEntity.missionStates != null && hozomListEntity.missionStates.size() > 0) {
                    myHozomAdapter.setNewData(hozomListEntity.missionStates);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(DayTaskActivity.this, LoginActivity2.class));
                    }
                }
                super.onError(e, body);
                srl.setRefreshing(false);
            }
        });
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 2:
                    AnimationUtils.showAndHiddenAnimation(ll_hozom_finish, AnimationUtils.AnimationState.STATE_HIDDEN, 500);
                    break;
            }

            return false;
        }
    });

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @OnClick({R.id.btn_finish, R.id.iv_gantan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.iv_gantan:
                TipsPopupWindow popupWindow = TipsPopupWindow.getInstance(DayTaskActivity.this);
                popupWindow.show(iv_gantan);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case EventBusEntity.CODE_107:
                initData();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        initData();
    }
}
